<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div slot="header">
          <span>{{ isedit? '修改试题': '试题录入'}}</span>
        </div>
        <el-form
          label-width="100px"
          :rules="rules"
          :model="formData"
          ref="formquestions"
        >
        <!-- 学科选项 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              class="select"
              v-model="formData.subjectID"
              placeholder="请选择"
              @change="toLinkage"
            >
              <el-option
                v-for="item in subjectlist"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 目录选项 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select
              class="select"
              v-model="formData.catalogID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in directorylist"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 企业选项 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              class="select"
              v-model="formData.enterpriseID"
              placeholder="请选择"
            >
              <el-option
                v-for="item in enterpriselist"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 城市选项 -->
          <el-form-item label="城市：" prop="province">
            <el-select
              v-model="formData.province"
              style="width: 198px; margin-right: 4px"
              @change="getCityData"
            >
              <el-option
                v-for="item in provinceList"
                :key="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select v-model="formData.city" style="width: 198px">
              <el-option
                v-for="item in cityList"
                :key="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向选项 -->
          <el-form-item label="方向：" prop="direction">
            <el-select
              class="select"
              v-model="formData.direction"
              placeholder="请选择"
            >
              <el-option
                v-for="item in direction"
                :key="item"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 题型选项 -->
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group v-model="formData.questionType">
              <el-radio
                v-for="item in questionType"
                :label="item.value +''"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="formData.difficulty">
              <el-radio
                v-for="item in myDifficulty"
                :label="item.value +''"
                :key="item.value"
                :value="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干：" prop="question">
            <quill-editor
              class="editor-container"
              v-model="formData.question"
            ></quill-editor>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item
            label="选项："
            v-if="formData.questionType != 3"
            style="margin-top: 100px"
          >
          <!-- 不同的题型渲染单选或多选 -->
            <div class="flex" v-for="item in formData.options" :key="item.code">
              <el-radio
                v-if="formData.questionType == 1"
                v-model="formData.isSelect"
                :label="item.code"
                style="margin-right: 5px"
                @input="editSelect"
              ></el-radio>
              <el-checkbox
                v-if="formData.questionType == 2"
                v-model="item.isRight"
                :label="item.code"
                style="margin-right: 5px"
              ></el-checkbox>
              <!-- 输入框 -->
              <el-input v-model="item.title" class="radio-input" />
              <!-- 上传图片 -->
              <el-upload
                class="avatar-uploader"
                action=""
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="
                  (e) => {
                    uploadImage(e, item.code);
                  }
                "
              >
                <img v-if="item.img" :src="item.img" class="avatar" />
                <p v-else>上传图片</p>
                <i class="el-icon-circle-close close"></i>
              </el-upload>
            </div>
            <el-button type="danger" @click="addoptions">+增加选项与答案</el-button>
            <!-- 解析视频 -->
          </el-form-item>
          <el-form-item> </el-form-item>
          <el-form-item label="解析视频：">
            <el-input v-model="formData.videoURL" class="select"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析：" prop="answer">
            <quill-editor
              v-model="formData.answer"
              class="editor-container"
            ></quill-editor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注：" style="margin-top: 100px">
            <el-input
              class="select"
              v-model="formData.remarks"
              type="textarea"
            ></el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签：" prop="tags">
            <el-select v-model="tagsarr" multiple @change="arrUpdatestring">
              <el-option
                v-for="item in tagslist"
                :value="item.label"
                :key="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addtestquestions"
              >{{ isedit?'确认修改': '确认提交'}}</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
import { difficulty, questionType, direction } from '../../api/hmmm/constants'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
// import 'quill/dist/quill.bubble.css'
import { provinces, citys } from '@/api/hmmm/citys'
import { quillEditor } from 'vue-quill-editor'
import { simple as simple1 } from '../../api/hmmm/subjects'
import { add, detail, update } from '../../api/hmmm/questions'
import { simple as simple2 } from '../../api/hmmm/directorys'
import { list } from '../../api/hmmm/companys'
import { simple as simple3 } from '../../api/hmmm/tags'
export default {
  components: {
    quillEditor
    // Citys
  },
  data () {
    return {
      tagsarr: [],
      isedit: false,
      provinceList: [], // 市
      cityList: [], // 区
      subjectlist: [], // 学科列表
      directorylist: [], // 目录
      enterpriselist: [], // 企业
      myDifficulty: difficulty, // 难度
      questionType: questionType, // 题型
      direction: direction, // 方向
      tagslist: [], // 试题标签
      formData: {
        city: '', // 地区
        province: '', // 城市
        isSelect: '', // 单选
        subjectID: '', // 学科id
        catalogID: '', // 目录id
        enterpriseID: '', // 企业id
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          // 选项
          {
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: ['blur', 'change'] }],
        catalogID: [{ required: true, message: '请选择目录', trigger: ['blur', 'change'] }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: ['blur', 'change'] }
        ],
        province: [{ required: true, message: '请选择地区', trigger: ['blur', 'change'] }],
        direction: [{ required: true, message: '请选择方向', trigger: ['blur', 'change'] }],
        questionType: [
          { required: true, message: '请选择题型', trigger: ['blur', 'change'] }
        ],
        difficulty: [{ required: true, message: '请选择难度', trigger: ['blur', 'change'] }],
        question: [{ required: true, message: '请输入题干', trigger: ['blur', 'change'] }],
        answer: [{ required: true, message: '请输入解析', trigger: ['blur', 'change'] }],
        tags: [{ required: true, message: '请选择标签', trigger: ['blur', 'change'] }]
      }
    }
  },
  created () {
    this.getsubject() // 获取学科列表
    this.getenterprise() // 企业简单列表
    this.getCityData() // 城市列表
    this.toEdit() // 回显
  },
  mounted () {
    console.log(this.$route.params.id)
  },
  methods: {
    // 获取学科简单选项
    async getsubject () {
      const res = await simple1()
      console.log(res)
      this.subjectlist = res.data
    },
    async toLinkage (subjectID) {
      // console.log(val)
      const res = await simple2({ subjectID })
      this.directorylist = res.data
      const ress = await simple3({ subjectID })
      console.log(res)
      this.tagslist = ress.data
    },
    // 企业简单列表
    async getenterprise () {
      const res = await list()
      console.log(res)
      this.enterpriselist = res.data.items
    },
    // 获取市
    getCityData () {
      this.formData.city = ''
      this.provinceList = provinces()
      if (this.formData.province) {
        this.cityList = citys(this.formData.province)
      }
    },
    // 添加或编辑
    addtestquestions () {
      this.$refs.formquestions.validate((isok) => {
        console.log(isok)
        if (isok) {
          this.isedit ? this.updatequestions() : this.addquestions()
        } else {
          console.log(1)
          this.$message.error('请填必填项')
        }
      })
    },
    // 编辑
    async updatequestions () {
      console.log('编辑')
      await update(this.formData)
      this.$message.success('编辑完成')
      this.$router.back()
    },
    // 添加
    async addquestions () {
      console.log('添加')
      await add(this.formData)
      this.$message.success('添加成功')
      this.$router.back()
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传图片
    uploadImage (e, code) {
      console.log(e, code)
      const cos = new COS({
        SecretId: 'AKIDeEfsrb9TYP1PZUByYxEJG1YqxrWxABqJ',
        SecretKey: 'JQK0ZxBScZKtELDtL6crxvfEaj1681iB'
      })
      cos.putObject(
        {
          Bucket: 'xiaoyang-1318397346' /* 填写自己的 bucket，必须字段 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
          Key: e.file
            .name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          Body: e.file, // 上传文件对象
          StorageClass: 'STANDARD' // 固定值
        },
        (err, data) => {
          if (data.statusCode === 200 && data.Location) {
            // 拿到了腾讯云返回的地址
            // 通过input自定义事件将地址传出去
            console.log(data.Location)
            this.formData.options.forEach((item) => {
              if (item.code === code) {
                item.img = 'http://' + data.Location
              }
            })
            // this.$emit('input', 'http://' + data.Location) // 将地址返回了
          } else {
            this.$message.error(err.Message) // 上传失败提示消息
          }
        }
      )
    },
    // 添加选项
    addoptions () {
      if (this.formData.options.length === 26) {
        return this.$message.error('你小子，不要添加了')
      }
      const newItem = {
        code: String.fromCharCode(this.formData.options.length + 65),
        title: '',
        img: '',
        isRight: false
      }
      this.formData.options.push(newItem)
    },
    // 点击题型选择框
    editSelect (val) {
      this.formData.options.forEach((item) => {
        item.isRight = false
        if (item.code === val) {
          item.isRight = true
        }
      })
    },
    // 回显
    async toEdit () {
      const id = this.$route.params.id || ':id'
      if (id === ':id') return
      this.isedit = true
      const res = await detail({ id })
      console.log(res)
      this.formData = res.data
      this.tagsarr = res.data.tags.split(',')
      if (res.data.remarks === '') {
        this.formData.remarks = ' '
      }
      if (res.data.videoURL === '') {
        this.formData.videoURL = ' '
      }
    },
    arrUpdatestring () {
      if (Array.isArray(this.tagsarr)) {
        this.formData.tags = this.tagsarr.join(',')
      }
    }
  },
  watch: {
    tagsarr: {
      deep: true,
      handler () {
        this.arrUpdatestring()
      }
    },
    'formData.videoURL': {
      deep: true,
      handler () {
        console.log(1)
        if (this.formData.videoURL === '') {
          this.formData.videoURL = ' '
        }
      }
    },
    'formData.remarks': {
      deep: true,
      handler () {
        if (this.formData.remarks === '') {
          this.formData.remarks = ' '
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.select {
  width: 400px;
}
.editor-container {
  height: 200px; /* 设置固定高度 */
}
.flex {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .radio-input {
    width: 250px;
    margin-right: 10px;
  }

  .avatar {
    width: 100px;
    display: block;
  }
  .radio-button {
    height: 70px;
    border-radius: 10px;
  }
  ::v-deep .avatar-uploader {
    .el-upload {
      position: relative;
      width: 100px;
      height: 60px;
      line-height: 30px;
      border: 1px dashed #dcdfe6;
      border-radius: 7px;
      margin-left: 5px;
      .close {
        color: #dcdfe6;
        position: absolute;
        top: -7px;
        right: -7px;
      }
      &:hover{
        border-color: #0caafa;
      }
    }
  }
}
</style>
